package org.changs.launcher.service;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.WindowManager;

import org.changs.aplug.base.BaseActivity;
import org.changs.aplug.utils.QRcodeUtils;
import org.changs.launcher.R;
import org.changs.launcher.databinding.QrCodeLayoutBinding;
import org.changs.launcher.device.DeviceConnectUtils;

import timber.log.Timber;

/**
 * Created by yincs on 2017/10/10.
 */

public class RemoteActivity extends BaseActivity {
    public static final String ACTION_SHOW_QRCODE = "action_show_qrcode";

    @Override
    public void setup(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        handle();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handle();
    }

    private void handle() {
        String action = getIntent().getAction();
        if (Intent.ACTION_VIEW.equals(action) && getIntent().getData() != null) {
            showQrCode(DeviceConnectUtils.genDeviceApJsonObject(this).toString());
        } else if ((ACTION_SHOW_QRCODE.equals(action))) {
            Uri data = getIntent().getData();
            Timber.d("action = " + action);
            Timber.d("data = " + data);
            showQrCode(data.toString());
        } else {
            finish();
        }
    }

    private void showQrCode(String data) {
        QrCodeLayoutBinding binding = DataBindingUtil.setContentView(this, R.layout.qr_code_layout);
        final Bitmap qrCode = QRcodeUtils.createQRCode(data, (int) getResources().getDimension(R.dimen.PX549));
        binding.ivCode.setImageBitmap(qrCode);
        binding.tvMsg.setText("打开手机APP,扫一扫联网");
        binding.btnClose.setOnClickListener(v -> finish());
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!isFinishing()) {
            finish();
        }
    }
}
